#!/bin/bash
#
#    /etc/rc.d/init.d/opennebula
#
# Starts the OpenNebula daemon
#
# chkconfig: 345 65 35
# description: Starts the OpenNebula daemon
# processname: opennebula

### BEGIN INIT INFO
# Provides: opennebula
# Required-Start: $local_fs $remote_fs
# Required-Stop: $local_fs $remote_fs
# Default-Start:  2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start and stop opennebula
# Description: start and stop opennebula
### END INIT INFO

prog="oned"

ONE_BIN=/usr/bin/one
LOCKFILE=/var/lock/subsys/${prog}

# Source function library.
. /etc/rc.d/init.d/functions

RETVAL=0

check() {
    # Check that we're a privileged user
    [ `id -u` = 0 ] || exit 4

    # Check if oned is executable
    test -x $ONE_BIN || exit 5
}

start() {
    check

    # Create run and lock directories
    mkdir -p /var/run/one
    chown oneadmin:oneadmin /var/run/one

    mkdir -p /var/lock/one
    chown oneadmin:oneadmin /var/lock/one

    echo -n $"Starting OpenNebula daemon: "
    daemon --user oneadmin $ONE_BIN start
    RETVAL=$?

    echo
    [ $RETVAL -eq 0 ] && touch $LOCKFILE

    return $RETVAL
}

stop() {
    check

    echo -n $"Stopping OpenNebula daemon: "
    daemon --user oneadmin $ONE_BIN stop
    RETVAL=$?

    [ $RETVAL -eq 0 ] && success || failure
    echo
    [ $RETVAL -eq 0 ] && rm -f $LOCKFILE

    return $RETVAL
}

start-sched() {
    echo -n $"Starting OpenNebula scheduler: "
    daemon --user oneadmin $ONE_BIN start-sched
    RETVAL=$?

    [ $RETVAL -eq 0 ] && success || failure
    echo
    [ $RETVAL -eq 0 ] && rm -f $LOCKFILE

    return $RETVAL
}

stop-sched() {
    echo -n $"Stopping OpenNebula scheduler: "
    daemon --user oneadmin $ONE_BIN stop-sched
    RETVAL=$?

    [ $RETVAL -eq 0 ] && success || failure
    echo
    [ $RETVAL -eq 0 ] && rm -f $LOCKFILE

    return $RETVAL
}

restart() {
    stop
    start
}

restart-sched() {
    stop-sched
    sleep 1
    start-sched
}


case "$1" in
start)
    start
    ;;
stop)
    stop
    ;;
restart)
    restart
    ;;
restart-sched)
    restart-sched
    ;;
status)
    status $prog
    RETVAL=$?
    ;;
*)
    echo $"Usage: $0 {start|stop|status|restart}"
    RETVAL=2
esac

exit $RETVAL
